<template>
  <div style="margin: 4rem"></div>
  <el-main>
    <el-form
      :rules="loginRules"
      ref="loginRef"
      :label-position="labelPosition"
      label-width="100px"
      :model="formUser"
      style="max-width: 460px"
      size="large"
    >
      <el-form-item label="用户名:" prop="name">
        <el-input v-model="formUser.name"></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="formUser.password" type="password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleLogin(this.formUser)">
          登录
        </el-button>
        <el-button type="info" @click="showRegister()"> 注册 </el-button>
      </el-form-item>
    </el-form>
  </el-main>

  <Register :isVisiable="isOpen"></Register>
</template>


<script>
import { getCurrentInstance, reactive, ref } from 'vue'
import Register from './Register.vue'
import store from '../store'
import { ElMessage } from 'element-plus'
export default {
  components: {
    Register
  },
  setup () {
    const { proxy } = getCurrentInstance()
    const labelPosition = ref('right')
    const isOpen = ref(false)
    const loginRules = {
      name: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
      password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
      code: [{ required: true, trigger: "change", message: "请输入验证码" }]
    }
    const formUser = reactive({
      name: '',
      password: '',
    })
    return {
      formUser,
      isOpen,
      labelPosition,
      loginRules,
      proxy
    }
  },
  methods: {
    //登录
    handleLogin () {
      this.proxy.$refs.loginRef.validate(valid => {
        if (!valid) return
        //调用store登录
        store.dispatch("Login", this.formUser).then(() => {
          ElMessage({
            message: "<font color='black'>欢迎回来 " + this.formUser.name + "</font>",
            type: "success",
            dangerouslyUseHTMLString: true
          })
          this.$router.push("/Main")
        })
      })
    },
    //弹出注册页
    showRegister () {
      if (this.isOpen = "true") {
        this.isOpen = "false"
      }
      this.isOpen = "true"



    }
  }
}
</script>